package com.rzico.sbl.ui.manager

import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import com.lzg.extend.jackson.JsonUtil
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityPickupGoodsBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.PickData
import com.rzico.sbl.model.PickGoodsData
import com.rzico.sbl.other.showMemoDialog
import com.rzico.sbl.other.showPriceDialog
import com.rzico.sbl.ui.goods.GoodsActivity
import com.rzico.sbl.viewmodel.PickupViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.bottomHide
import com.xinnuo.common.helper.bottomShow
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.addOnScrollChanged
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter

class PickupGoodsActivity : BaseActivity(R.layout.activity_pickup_goods) {

    private val mBinding by lazy { ActivityPickupGoodsBinding.bind(getRootView()) }

    private lateinit var mPickupId: String
    private lateinit var mActionMode: String
    private var mKeyWord = ""

    override fun getViewModel() = get<PickupViewModel>()

    override fun initData() {
        setToolbarVisibility(isVisible = false)

        initLayout()
        initSearch()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout
                    .emptyHint
                    .text = "暂无相关商品信息！"

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    layout.addItemDecoration(SpaceTBDecoration(bottom = 60f))
                    layout.addOnScrollChanged(
                        onShow = { mBinding.goodsBottom.bottomShow() },
                        onHide = { mBinding.goodsBottom.bottomHide(55f) }
                    )

                    mAdapter = SlimAdapter.creator()
                        .register<PickGoodsData>(R.layout.item_pickup_goods) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_pick_name, bean.name)
                                text(R.id.item_pick_price, bean.price.formatDecimal())
                                text(R.id.item_pick_stock, bean.stock)

                                visibility(
                                    R.id.item_pick_has,
                                    visibleValue { bean.stock.intValue == 0 }
                                )

                                visibility(
                                    R.id.item_pick_jian,
                                    goneValue { bean.stock.intValue == 0 }
                                )

                                with<ImageView>(R.id.item_pick_img) {
                                    it.loadImage(bean.thumbnail)
                                }

                                clicked(R.id.item_pick_change) {
                                    updatePrice(bean.id, bean.name, bean.price, index)
                                }

                                clicked(R.id.item_pick_jian) {
                                    decreaseStock(bean.id, index)
                                }

                                clicked(R.id.item_pick_jia) {
                                    increaseStock(bean.id, index)
                                }

                                clicked {
                                    when (mActionMode) {
                                        // 自提柜添加或更换商品
                                        "single" -> {
                                            (bean.stock.intValue == 0)
                                                .condition {
                                                    showToast("该商品库存不足，请先添加库存")
                                                    return@clicked
                                                }

                                            bean.position = intent.getIntExtra("index", -1)

                                            // 刷新自提柜商品
                                            LiveEventBus
                                                .get("cupboardCode")
                                                .post(bean)

                                            finishView()
                                        }
                                    }
                                }

                                longClicked {
                                    deleteGoods(bean.id, index)
                                    true
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }
    }

    private fun initSearch() {
        mBinding
            .goodsSearch
            .apply {
                searchEdit.hint = "请输入商品名称"
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        (it.isEmpty() && mKeyWord.isNotEmpty())
                            .condition {
                                mKeyWord = ""
                                updateList()
                            }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    (actionId == EditorInfo.IME_ACTION_SEARCH)
                        .condition {
                            hideSoftInput() //隐藏软键盘

                            searchEdit.text
                                .isBlank()
                                .conditionElse(
                                    actionTrue = { showToast("请输入商品名称") },
                                    actionFalse = {
                                        mKeyWord = searchEdit.textTrim
                                        updateList()
                                    }
                                )
                        }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    searchEdit.text
                        .isBlank()
                        .conditionElse(
                            actionTrue = { showToast("请输入商品名称") },
                            actionFalse = {
                                mKeyWord = searchEdit.textTrim
                                updateList()
                            }
                        )
                }
            }
    }

    override fun initListener() {
        mPickupId = intent.getExtra("pickId")
        mActionMode = intent.getExtra("mode")

        mBinding
            .btAdd
            .oneClick {
                startActivityEx<GoodsActivity>(
                    "mode" to "multiple",
                    "hint" to "请选择要添加的自提点商品"
                )
            }

        observe<String>("goodsMultiple") {
            getViewModel()
                .delay {
                    getViewModel()
                        .requestBind(
                            requestUrl = BaseUrl.mngPickProA,
                            params = arrayOf(
                                "shopId" to mPickupId,
                                "ids" to it
                            )
                        )
                        .bindLifeCycle(getLifecycleOwner())
                        .subscribeBySuccess(
                            event = getViewModel(),
                            onSuccess = {
                                showToast("添加商品成功！")

                                updateList()
                            }
                        )
                }
        }
    }

    /**
     * 商品改价
     */
    private fun updatePrice(
        stockId: String,
        stockName: String,
        amount: String,
        index: Int
    ) {
        showPriceDialog(
            title = "商品改价",
            hint = stockName,
            default = amount,
            onSure = { value ->
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.mngPickPri,
                        params = arrayOf(
                            "stockId" to stockId,
                            "price" to value
                        ),
                        onSuccess = {
                            showToast("商品改价成功！")

                            (index < 0)
                                .conditionElse(
                                    actionTrue = ::updateList,
                                    actionFalse = {
                                        (mList[index] as PickGoodsData).price = value
                                        mAdapter.notifyItemChanged(index)
                                    }
                                )
                        }
                    )
            }
        )
    }

    /**
     * 增加商品库存
     */
    private fun increaseStock(itemId: String, index: Int) {
        showMemoDialog(
            title = "增加库存",
            hint = "请输入增加库存数",
            inputType = "number",
            canEmpty = false
        ) { result ->
            getViewModel()
                .request(
                    requestUrl = BaseUrl.mngPickSto,
                    params = arrayOf(
                        "shopId" to mPickupId,
                        "stockId" to itemId,
                        "type" to 0,
                        "editStock" to result
                    ),
                    onSuccess = { json ->
                        showToast("库存修改成功！")

                        val item = mList[index] as PickGoodsData
                        item.stock = (item.stock.intValue + result.intValue).toString()
                        mAdapter.notifyItemChanged(index)

                        // 刷新站点列表
                        JsonUtil.jsonToBean(
                            json,
                            PickData::class.java
                        )?.let {
                            it.extend = "update"

                            LiveEventBus
                                .get("pickList")
                                .post(it)
                        }
                    }
                )
        }
    }

    /**
     * 减少商品库存
     */
    private fun decreaseStock(itemId: String, index: Int) {
        showMemoDialog(
            title = "减少库存",
            hint = "请输入减少存数",
            inputType = "number",
            canEmpty = false
        ) { result ->
            getViewModel()
                .request(
                    requestUrl = BaseUrl.mngPickSto,
                    params = arrayOf(
                        "shopId" to mPickupId,
                        "stockId" to itemId,
                        "type" to 1,
                        "editStock" to result
                    ),
                    onSuccess = { json ->
                        showToast("库存修改成功！")

                        val item = mList[index] as PickGoodsData
                        item.stock = (item.stock.intValue - result.intValue).toString()
                        mAdapter.notifyItemChanged(index)

                        // 刷新站点列表
                        JsonUtil.jsonToBean(
                            json,
                            PickData::class.java
                        )?.let {
                            it.extend = "update"

                            LiveEventBus
                                .get("pickList")
                                .post(it)
                        }
                    }
                )
        }
    }

    /**
     * 删除商品
     */
    private fun deleteGoods(itemId: String, index: Int) {
        showHintDialog(
            title = "自提商品",
            hint = "确定要删除该自提商品吗？",
            sure = "删除",
            onSure = {
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.mngPickProD,
                        params = arrayOf(
                            "shopId" to mPickupId,
                            "ids" to itemId
                        ),
                        onSuccess = {
                            showToast("自提商品删除成功！")

                            mList.removeAt(index)
                            mAdapter.apply {
                                notifyItemRemoved(index)
                                notifyItemRangeChanged(index, mList.size - index)
                            }

                            mBinding
                                .listLayout
                                .emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                    )
            }
        )
    }

    /**
     * 商品列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .goodsList(
                page = index,
                shopId = mPickupId,
                keyWord = mKeyWord,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}